import axios, { AxiosRequestConfig } from "axios";
const pendingRequest = new Map();
/**获取独一无二的键名函数 */
const generateReqKey = (config: AxiosRequestConfig<any>) => {
  const { method, url, params, data } = config;
  return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&");
};
/**添加键值对函数：添加取消请求函数（值） */
export const addPendingRequest = (config: AxiosRequestConfig<any>) => {
  const requestKey = generateReqKey(config);
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken(cancel => {
      if (!pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, cancel);
      }
    });
};
/**取消重复请求函数 */
export const removePendingRequest = (config: AxiosRequestConfig<any>) => {
  const requestKey = generateReqKey(config);
  if (pendingRequest.has(requestKey)) {
    const cancelToken = pendingRequest.get(requestKey);
    cancelToken(requestKey);
    pendingRequest.delete(requestKey);
  }
};
